package ucd.csi.comp30220.fall2011.oteop.flughafen.impl;

import java.util.ArrayList;
import java.util.List;

import ucd.csi.comp30220.fall2011.oteop.flight.FlightFinder;
import ucd.csi.comp30220.fall2011.oteop.flight.FlightInfo;
import ucd.csi.comp30220.fall2011.oteop.traffic.TrafficFinder;

public class Dispatcher {
    
    private ArrayList<FlightInfo> infos = new ArrayList<FlightInfo>();
    
    public Dispatcher() {
        new Thread(new Runnable() {
            public void run() {
                dispatch();
            }
        }).start();
    }
    
    public void acceptFlight(FlightInfo flightInfo) {
        infos.add(flightInfo);
    }
    
    private void dispatch() {
        while (true) {
            try { 
                Thread.sleep(4*1000);
                ArrayList<FlightInfo> inf = (ArrayList<FlightInfo>)infos.clone();
                for (FlightInfo info : inf) {
                    if (info.getDepartureDateTime().getTime() <= System.currentTimeMillis()) {
                        infos.remove(info);
                        FlightFinder.find(info.getNumber()).start();
                        TrafficFinder.find(
                            info.getDepartureAirportInfo().getName()).handleFlight(info.getNumber());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
